<script setup>
import { useUsersStore } from '@/stores/usersStore';
import { useRecordsStore } from '@/stores/recordsStore';
import ItemEntry from '@/components/ItemEntry.vue';
import AddButton from '@/components/AddButton.vue';
import { useRoute } from 'vue-router';
import { onMounted, ref, computed } from 'vue';
//添加登录验证功能
import { useLoginStore } from '@/stores/loginStore';
const loginStore = useLoginStore();
loginStore.actions.loadLogin();
const login = ref(loginStore.state.login);


const route = useRoute();
const usersStore = useUsersStore();
const recordsStore = useRecordsStore();
usersStore.actions.loadUsers(login.value.uuid, login.value.token);
const uuid = route.params.uuid;
const records = ref(null);
recordsStore.actions.loadRecords(uuid).then(() => {
    records.value = recordsStore.state.records;
});
const refleshRecords = () => {
    recordsStore.actions.loadRecords(uuid).then(() => {
        records.value = recordsStore.state.records;
    });
}
const handleSubmit = (data) => {
    recordsStore.actions.addRecord(data, login.value.uuid, login.value.token).then(() => {
        alert("添加成功");
        refleshRecords();
    });
}
const handelUpdate = (data) => {
    console.log(data);
    recordsStore.actions.updateRecord(data, login.value.uuid, login.value.token).then(() => {
        refleshRecords();
    });
}
const formatCurrency = (value) => {
    return '¥' + value.toFixed(2).replace(/\B(?=(\d{3})+(?!\d))/g, ',')
}
//分组
const groupedRecords = computed(() => {
    const sortedRecords = [...records.value].sort((a, b) => b.time - a.time);
    return sortedRecords.reduce((acc, record) => {
        const date = new Date(record.time * 1000);
        const year = date.getFullYear();
        const month = date.getMonth() + 1;
        const day = date.getDate();
        if (!acc[year]) {
            acc[year] = {};
        }
        if (!acc[year][month]) {
            acc[year][month] = {
                monthlyTotal: 0,
                days: {}
            };
        }
        if (!acc[year][month].days[day]) {
            acc[year][month].days[day] = {
                dailyTotal: 0,
                records: []
            }
        }
        acc[year][month].monthlyTotal += record.count * record.amount;
        acc[year][month].days[day].dailyTotal += record.count * record.amount;
        acc[year][month].days[day].records.push(record);
        return acc;
    }, {});
})
// 年份从大到小
const sortedYears = computed(() => {
    return Object.keys(groupedRecords.value).sort((a, b) => b - a)
})

// 同一年的月份从大到小
function sortedMonths(year) {
    return Object.keys(groupedRecords.value[year]).sort((a, b) => b - a)
}
// 同一月的天数从大到小
function sortedDays(year, month) {
    return Object.keys(groupedRecords.value[year][month].days).sort((a, b) => b - a)
}
import { useRouter } from 'vue-router';
const router = useRouter();
function handleBack() {
    router.push('/users');
}
function handleCopy() {
    let copyText = "";
    copyText = window.location.href;
    let inputNode = document.createElement("input");
    inputNode.value = copyText;
    document.body.appendChild(inputNode);
    inputNode.select();
    document.execCommand("copy");
    document.body.removeChild(inputNode);
    alert("复制成功");
}
</script>
<template>
    <div class="user-view">
        <div class="header" v-if="login.login">

            <h2 class="back" @click="handleBack">返回</h2>
            <h2 class="copy" @click="handleCopy">复制</h2>
        </div>
        <div v-for="year in sortedYears">
            <div v-for="month in sortedMonths(year)" class=" month-card">
                <h1>{{ year }}年{{ month }}月-合计{{ formatCurrency(groupedRecords[year][month].monthlyTotal) }}</h1>
                <div v-for="day in sortedDays(year, month)" class="day-card">
                    <h2>{{ day
                        }}日-合计{{ formatCurrency(groupedRecords[year][month].days[day].dailyTotal) }}</h2>
                    <ul class="record-list">
                        <li v-for="item in groupedRecords[year][month].days[day].records" class="record">
                            <ItemEntry :item=item @update="handelUpdate" :users="usersStore.state.users"
                                :isLogin="login.login" @cancel="" />
                        </li>
                    </ul>
                </div>
            </div>
        </div>
        <AddButton :userName=route.params.uuid @reflesh="refleshRecords" @submit="handleSubmit" v-if="login.login" />
    </div>
</template>

<style>
body {
    background-color: #F5F5F5;
}

.header {
    display: flex;
    font-size: 1.0rem;
    font-weight: bolder;
    color: #4CAF50;

    justify-content: space-between;
    margin-left: 10px;
    margin-right: 10px;
}

.user-view {
    width: 100vw;
}

.record {
    list-style-type: none;
}

.record-list {
    padding: 0;
}

.month-card {
    border-radius: 15px 15px 0 0;
    background-color: white;

    margin-bottom: 20px;
    margin-left: 10px;
    margin-right: 10px;

}

.month-card h1 {
    white-space: nowrap;
    font-size: 1.5rem;
    font-weight: bolder;
    margin-left: 5px;
}

.day-card {
    background-color: white;
    padding-left: 10px;
    padding-right: 10px;
}

.day-card h2 {
    white-space: nowrap;
    font-size: 1.1rem;
    font-weight: 600;
}
</style>